<template>
  <div
    class="roc-scale-box"
    ref="rocScaleBox"
    :style="{
      ...style,
      width: width + 'px',
      height: height + 'px',
      backgroundColor: bgc
    }"
  >
    <slot></slot>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
    return {
      defaulstyle: {
        position: 'fixed',
        transform: 'scale(var(--scale)) translate(-50%, -50%)',
        transformOrigin: '0 0',
        left: '50%',
        top: '50%',
        zIndex: 999
      },
      scale: 1,
      scaleX: 1,
      scaleY: 1
    }
  },
  props: {
    width: {
      type: Number,
      default: 1920
    },
    height: {
      type: Number,
      default: 1080
    },
    bgc: {
      type: String,
      default: 'transparent'
    },
    delay: {
      type: Number,
      default: 100
    },
    isFlat: {
      type: Boolean,
      default: true
    }
  },
  mounted() {
    this.setScale()
    window.addEventListener('resize', _.throttle(this.setScale, this.delay))
  },
  computed: {
    style() {
      // 拉伸模式
      if (this.isFlat) {
        return {
          ...this.defaulstyle,
          transform: 'scaleX(var(--scaleX)) scaleY(var(--scaleY)) translate(-50%, -50%)'
        }
      } else {
        // 等比缩放模式
        return {
          ...this.defaulstyle,
          transform: 'scale(var(--scale)) translate(-50%, -50%)'
        }
      }
    }
  },
  methods: {
    setScale() {
      if (this.$refs.rocScaleBox) {
        if (this.isFlat) {
          // 拉伸模式
          this.scaleX = this.getScaleX()
          this.scaleY = this.getScaleY()
          this.$refs.rocScaleBox.style.setProperty('--scaleX', this.scaleX)
          this.$refs.rocScaleBox.style.setProperty('--scaleY', this.scaleY)
        } else {
          // 等比缩放模式
          this.scale = this.getScale()
          this.$refs.rocScaleBox.style.setProperty('--scale', this.scale)
        }
      }
    },
    getScaleX() {
      const ww = window.innerWidth / this.width
      return ww
    },
    getScaleY() {
      const wh = window.innerHeight / this.height
      return wh
    },
    getScale() {
      const wh = window.innerHeight / this.height
      const ww = window.innerWidth / this.width
      return ww < wh ? ww : wh
    }
  }
}
</script>

<style lang="scss" scoped></style>
